export default function(vdom, container) {
  container.innerHTML = ''
  container.appendChild(createElement(vdom))
}

const createElement = vdom => {
  const [type, props, ...children] = vdom
  if ('function' === typeof type) {
    if (type.prototype && 'function' === typeof type.prototype.render) {
      const Component = type
      // 解构 props
      const component = new Component({ ...props, children })
      if ('function' === typeof component.beforeRender) {
        component.beforeRender()
      }
      // 递归 call
      return createElement(component.render())
    }
    const component = type
    // 递归 call
    // 解构 props
    return createElement(component({ ...props, children }))
  }
  const element = document.createElement(type)
  for (let key in props) {
    if (key in element) {
      element[key] = props[key]
    } else {
      element.setAttribute(key, props[key])
    }
  }
  children.forEach(child => {
    const childNode = createChild(child)
    if (childNode) {
      element.appendChild(childNode)
    }
  })
  return element
}

const createChild = child => {
  if (Array.isArray(child)) {
    // recursive call
    return createElement(child)
  } else if (child && 'boolean' !== typeof child) {
    return document.createTextNode(child)
  }
}